import React, { Component } from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'

import './style.less'

class LoadMore extends Component {
  constructor(props) {
    super(props);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
  }

  handleLoadMore() {
    this.props.loadMore();
  }

  componentDidMount() {
    //滚动到低端时加载更多
    const wrapper = this.refs.wrapper;
    let timeoutId;
    let callback = () => {
      const top = wrapper.getBoundingClientRect().top;
      const windowHeight = window.screen.height;
      if(top && top < windowHeight){
        this.props.loadMore();
      }
    }
    window.addEventListener('scroll', () => {
      if(this.props.isLoadingMore){
        return
      }
      if(timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(callback, 50);
    });
  }

  render() {
    return (
      <div className="load-more" ref="wrapper">
        {
          this.props.isLoadingMore
          ? <span>加载中...</span>
          : <span onClick={this.handleLoadMore.bind(this)}>加载更多</span>
        }
      </div>
    )
  }
}

export default LoadMore
